package com.techwells.learningkites.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.lidroid.xutils.BitmapUtils;
import com.techwells.learningkites.R;
import com.techwells.learningkites.adapter.CourseExpandListAdapter;
import com.techwells.learningkites.adapter.CourseExpandListAdapter.CellHolderChild;
import com.techwells.learningkites.adapter.CourseListAdapter;
import com.techwells.learningkites.adapter.CourseViewPagerAdapter;
import com.techwells.learningkites.base.KitesApplication;
import com.techwells.learningkites.controller.LoginActivity;
import com.techwells.learningkites.controller.MainPageActivity;
import com.techwells.learningkites.controller.RegisterAcitivity;
import com.techwells.learningkites.controller.VideoDetailActivity;
import com.techwells.learningkites.controller.VideoListActivity;
import com.techwells.learningkites.database.CourseCategoryDao;
import com.techwells.learningkites.database.CourseCategoryDao.Properties;
import com.techwells.learningkites.database.DaoMaster;
import com.techwells.learningkites.database.DaoMaster.DevOpenHelper;
import com.techwells.learningkites.database.DaoSession;
import com.techwells.learningkites.model.MainPageViewModel;
import com.techwells.learningkites.networkaccess.KitesRequestUrl;
import com.techwells.learningkites.networkservice.KitesServiceMediator;
import com.techwells.learningkites.networkservice.model.Course;
import com.techwells.learningkites.networkservice.model.CourseCategory;
import com.techwells.learningkites.networkservice.model.Lesson;
import com.techwells.taco.mvvm.Route;
import com.techwells.taco.tasktool.TaskToken;
import com.techwells.taco.utils.ToastUtils;
import com.techwells.taco.widget.DbService;

import de.greenrobot.dao.query.QueryBuilder;

import android.R.integer;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView.ScaleType;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;

public class CourseFragment extends Fragment implements OnItemClickListener, OnChildClickListener {
	
	private ExpandableListView courseListView;
//	private List<CourseCategory> courseList;
	private List<Lesson> lessonList;
//	private CourseListAdapter courseListAdapter;
	private CourseExpandListAdapter courseListAdapter;
	
	private ViewGroup tipGroup;
	private ImageView[] tips;
	private List<View> dots;
	private CourseViewPagerAdapter courseViewPagerAdapter;
	private ViewPager coursevViewPager;
	private int currentItem = 0;
	private List<View> vpViews;
	private View vpView1,vpView2,vpView3;
	
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			coursevViewPager.setCurrentItem(currentItem + 1);
		};
	};
	private Timer mTimer;
	private TimerTask mTimerTask;
	
	
	private List<CourseCategory> courseCategoriesList;
	private MainPageActivity activity;
	private BitmapUtils bitmapUtils;
	private List<Course> courseList;
	private List<List<Course>> allCourseList;
	private int requestNum = 0;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_course, container,false);
	}

	
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		activity = (MainPageActivity) getActivity();
		initViews();
		initViewPager();
		
	}


	private void initViewPager() {
		coursevViewPager = (ViewPager) getActivity().findViewById(R.id.vp_course);
		vpView1 = getActivity().getLayoutInflater().inflate(
				R.layout.viewpager_ad1, null);
		vpView2 = getActivity().getLayoutInflater().inflate(
				R.layout.viewpager_ad2, null);
		vpView3 = getActivity().getLayoutInflater().inflate(
				R.layout.viewpager_ad3, null);
		vpViews = new ArrayList<View>();
		vpViews.add(vpView1);
		vpViews.add(vpView2);
		vpViews.add(vpView3);
		vpView1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				Intent intent = new Intent(getActivity(),RegisterAcitivity.class);
//				startActivity(intent);
			}
		});
		
		
		 tipGroup = (ViewGroup) getActivity().findViewById(R.id.tip_group);
		 tips = new ImageView[vpViews.size()];
		 for (int i = 0; i < tips.length; i++) {
				ImageView imageView = new ImageView(getActivity());
//				imageView.setLayoutParams(new LayoutParams(5, 5));
				tips[i] = imageView;
				if (i == 0) {
					tips[i].setBackgroundResource(R.drawable.dot_selected);
				} else {
					tips[i].setBackgroundResource(R.drawable.dot);
				}

				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
						new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
								LayoutParams.WRAP_CONTENT));
				layoutParams.leftMargin = 5;
				layoutParams.rightMargin = 5;
				tipGroup.addView(imageView, layoutParams);
			}
		 courseViewPagerAdapter = new CourseViewPagerAdapter(getActivity(), vpViews);
		 coursevViewPager.setAdapter(courseViewPagerAdapter);
		 coursevViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
		 coursevViewPager.setCurrentItem(vpViews.size()*100);
	}


	private void initViews() {
		courseListView = (ExpandableListView) getActivity().findViewById(R.id.lv_course);
//		courseList = new ArrayList<Course>();
//		lessonList = new ArrayList<Lesson>();
//		for (int i = 0; i < 12; i++) {
//			Course course = new Course();
//			courseList.add(course);
//		}
//		Lesson lesson = new Lesson();
//		lessonList.add(lesson);
//		courseListAdapter = new CourseExpandListAdapter(getActivity(), courseList,lessonList,this);
//		courseListView.setAdapter(courseListAdapter);
	}


	
	public class MyOnPageChangeListener implements OnPageChangeListener {
		
		
		@Override
		public void onPageScrollStateChanged(int arg0) {
			
		}

		// 当当前页面被滑动时调用
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		// 当新的页面被选中时调用
		@Override
		public void onPageSelected(int item) {			
			currentItem = item;	
			doTimerTask();
			if (item > vpViews.size()) {
				item = item % vpViews.size();
			}			
			
			for (int i = 0; i < tips.length; i++) {
				if (i == item) {
					tips[i].setBackgroundResource(R.drawable.dot_selected);
				} else {
					tips[i].setBackgroundResource(R.drawable.dot);
				}
			}
		}

	}
	
	private void doTimerTask(){
		if(mTimer != null){
			mTimer.cancel();			
		}
		mTimer = new Timer();
		if(mTimerTask != null ){
			mTimerTask.cancel();				
		}
		mTimerTask= new TimerTask() {
				
				@Override
				public void run() {
					Message msg = new Message();
					handler.sendMessage(msg);
					
				}
			};
		
		mTimer.schedule(mTimerTask, 2000);
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Route.route().nextController(getActivity(), VideoDetailActivity.class.getName(), Route.WITHOUT_RESULTCODE);
		
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}

	private void doRequestGetCourses(int courseCategoryId) {
		HashMap<String, Object> argMap = new HashMap<String, Object>();	
		argMap.put("courseCategoryId", courseCategoryId);
		activity.doTask(KitesServiceMediator.SERVICE_GET_COURSES,argMap);
		
	}
	

	public void refreshData(TaskToken token) {
		String method = token.method;
		if (method.equals(KitesServiceMediator.SERVICE_GET_COURSES_CATEGORIES)) {
			courseCategoriesList = ((MainPageViewModel)activity.baseViewModel).courseCategoriesList;
			allCourseList = new ArrayList<List<Course>>();
//			courseListAdapter = new CourseExpandListAdapter(getActivity(), courseCategoriesList,allCourseList);
//			courseListView.setAdapter(courseListAdapter);
//			courseListView.setOnChildClickListener(this);
			
			MainPageActivity.isRefresh ++;
			
			doRequestGetCourses(courseCategoriesList.get(0).id);
			
		}else if (method.equals(KitesServiceMediator.SERVICE_GET_COURSES)) {
			courseList = ((MainPageViewModel)activity.baseViewModel).courseList;
			allCourseList.add(courseList);
			requestNum++;
			if (requestNum < courseCategoriesList.size()) {
				doRequestGetCourses(courseCategoriesList.get(requestNum).id);
			}else {
//				courseListAdapter.notifyDataSetChanged();
				courseListAdapter = new CourseExpandListAdapter(getActivity(), courseCategoriesList,allCourseList);
				courseListView.setAdapter(courseListAdapter);
				courseListView.setOnChildClickListener(this);
			}
		}
		
	}


	@Override
	public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
			int arg3, long arg4) {
		if (allCourseList.size() != 0) {
			Intent intent = new Intent(getActivity(), VideoListActivity.class);
			intent.putExtra("courseId", allCourseList.get(arg2).get(arg3).id);
			Route.route().nextControllerWithIntent(getActivity(), VideoListActivity.class.getName(), Route.WITHOUT_RESULTCODE, intent);
		}
		return true;
	}


	
	
}
